#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<strings.h>
#include<string.h>

#include"Comm.hpp"

void Usage(const std::string& process)
{
    std::cout<<"Usage:"<<process<<"server_ip server_port"<<std::endl;
}
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    //1.创建socket
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    {
        std::cout<<"client_socke创建失败！"<<std::endl;
        exit(Socket_ERROR);
    }
    std::cout<<"client_socket创建成功！"<<std::endl;

    //填充server信息
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    while(true)
    {
        std::string inbuffer;
        std::cout<<"client# ";
        std::getline(std::cin,inbuffer);
        ssize_t n = sendto(sockfd,inbuffer.c_str(),inbuffer.size(),0,(struct sockaddr*)&server,sizeof(server));
        if(n>0)
        {
            //收消息
            char buffer[1024];
            struct sockaddr_in ret;
            socklen_t socklen  = sizeof(ret);
            ssize_t m = recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&ret,&socklen);
            if(m>0)
            {
                buffer[m] = 0;
                std::cout<<"server# ";
            }
            else
            {
                break;
            }
        }
        else
            break;

    }
    close(sockfd);
    return 0;
}